<template>
  <div class="guide-appointment-management">
    <div class="page-header">
      <h2>讲解预约管理</h2>
    </div>

    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="讲解员">
          <el-select v-model="searchForm.guideId" style="width: 100px;" placeholder="请选择讲解员" clearable>
            <el-option
              v-for="item in guideOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预约状态">
          <el-select v-model="searchForm.status" style="width: 100px;" placeholder="请选择状态" clearable>
            <el-option label="待审核" value="PENDING"></el-option>
            <el-option label="已通过" value="APPROVED"></el-option>
            <el-option label="已拒绝" value="REJECTED"></el-option>
            <el-option label="已取消" value="CANCELED"></el-option>
          </el-select>
        </el-form-item>
      
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="appointmentList"
        border
        style="width: 100%"
      >
        <el-table-column prop="id" label="预约编号" min-width="80"></el-table-column>
        <el-table-column prop="visitorName" label="预约人姓名" min-width="120"></el-table-column>
        <el-table-column prop="visitorPhone" label="联系电话" min-width="120"></el-table-column>
        <el-table-column prop="guideName" label="讲解员" min-width="120"></el-table-column>
        <el-table-column prop="appointmentDate" label="预约日期" min-width="120"></el-table-column>
        <el-table-column prop="timeSlotName" label="预约时段" min-width="120"></el-table-column>
        <el-table-column prop="visitorCount" label="参观人数" width="100"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" min-width="160"></el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="scope">
            <el-button 
              type="primary" 
              link 
              @click="handleDetail(scope.row)"
            >
              详情
            </el-button>
            <el-button 
              v-if="scope.row.status === 'PENDING'"
              type="success" 
              link 
              @click="handleAssignGuide(scope.row)"
            >
              分配讲解员
            </el-button>
            <el-button 
              v-if="scope.row.status === 'PENDING'"
              type="danger" 
              link 
              @click="handleCancel(scope.row)"
            >
              拒绝
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>
    </el-card>

    <!-- 详情弹窗 -->
    <el-dialog
      title="预约详情"
      v-model="detailDialogVisible"
      width="600px"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="预约编号">{{ detailData.id }}</el-descriptions-item>
        <el-descriptions-item label="预约人姓名">{{ detailData.visitorName }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ detailData.visitorPhone }}</el-descriptions-item>
        <el-descriptions-item label="讲解员">{{ detailData.guideName }}</el-descriptions-item>
        <el-descriptions-item label="预约日期">{{ detailData.appointmentDate }}</el-descriptions-item>
        <el-descriptions-item label="预约时段">{{ detailData.timeSlotName }}</el-descriptions-item>
        <el-descriptions-item label="参观人数">{{ detailData.visitorCount }}</el-descriptions-item>
        <el-descriptions-item label="预约藏品">{{ detailData.collectionNames || '未指定' }}</el-descriptions-item>
        <el-descriptions-item label="备注">{{ detailData.remark || '无' }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(detailData.status)">
            {{ getStatusText(detailData.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ detailData.createTime }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ detailData.updateTime }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分配讲解员弹窗 -->
    <el-dialog
      title="分配讲解员"
      v-model="assignDialogVisible"
      width="500px"
    >
      <el-form :model="assignForm" label-width="100px">
        <el-form-item label="预约编号">
          <span>{{ assignForm.appointmentId }}</span>
        </el-form-item>
        <el-form-item label="预约人">
          <span>{{ assignForm.visitorName }}</span>
        </el-form-item>
        <el-form-item label="预约日期">
          <span>{{ assignForm.appointmentDate }}</span>
        </el-form-item>
        <el-form-item label="讲解员" prop="guideId">
          <el-select v-model="assignForm.guideId" placeholder="请选择讲解员" style="width: 100%">
            <el-option
              v-for="item in availableGuides"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
              <div style="display: flex; justify-content: space-between; align-items: center">
                <span>{{ item.name }}</span>
                <span style="color: #8492a6; font-size: 13px">{{ item.phone }}</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="assignForm.remark" 
            type="textarea" 
            placeholder="请输入备注信息（可选）"
            :rows="3"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="assignDialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="submitting" @click="submitAssignment">确认分配</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAllGuides } from '@/api/guide'
import { getEnabledTimeSlots } from '@/api/timeSlot'
import { 
  getGuideAppointmentPage, 
  getGuideAppointmentById, 
  saveGuideAppointment,
  approveGuideAppointment 
} from '@/api/guideAppointment'

// 数据加载状态
const loading = ref(false)

// 列表数据
const appointmentList = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const guideOptions = ref([])
const timeSlotOptions = ref([])

// 搜索表单
const searchForm = reactive({
  id: '',
  guideId: '',
  status: '',
  appointmentDate: []
})

// 详情弹窗
const detailDialogVisible = ref(false)
const detailData = reactive({
  id: '',
  userId: '',
  guideId: '',
  guideName: '',
  appointmentDate: '',
  timeSlotId: '',
  timeSlotName: '',
  visitorName: '',
  visitorPhone: '',
  visitorCount: 0,
  collectionIds: '',
  collectionNames: '',
  status: '',
  remark: '',
  createTime: '',
  updateTime: ''
})

// 分配讲解员相关
const assignDialogVisible = ref(false)
const availableGuides = ref([])
const submitting = ref(false)
const assignForm = reactive({
  appointmentId: '',
  visitorName: '',
  appointmentDate: '',
  guideId: '',
  remark: ''
})

// 初始化
onMounted(() => {
  fetchGuideOptions()
  fetchTimeSlotOptions()
  fetchAppointmentList()
})

// 获取讲解员选项
const fetchGuideOptions = async () => {
  try {
    // 使用guide.js中的getAllGuides函数获取所有讲解员
    const response = await getAllGuides()
    
    guideOptions.value = response.filter(guide => guide.status === 1) || []
  } catch (error) {
    console.error('获取讲解员列表失败', error)
  }
}

// 获取时间段选项
const fetchTimeSlotOptions = async () => {
  try {
    const response = await getEnabledTimeSlots()
     
    timeSlotOptions.value = response|| []
  } catch (error) {
    console.error('获取时间段列表失败', error)
  }
}

// 获取讲解员名称
const getGuideName = (guideId) => {
  const guide = guideOptions.value.find(g => g.id === guideId)
  return guide ? guide.name : '未分配'
}

// 获取时间段名称
const getTimeSlotName = (timeSlotId) => {
  const timeSlot = timeSlotOptions.value.find(t => t.id === timeSlotId)
  return timeSlot ? `${timeSlot.startTime}-${timeSlot.endTime}` : '未知时段'
}

// 获取预约列表并处理讲解员和时间段信息
const fetchAppointmentList = async () => {
  loading.value = true
  try {
    // 处理日期范围
    let startDate, endDate
    if (searchForm.appointmentDate && searchForm.appointmentDate.length === 2) {
      startDate = searchForm.appointmentDate[0]
      endDate = searchForm.appointmentDate[1]
    }

    const params = {
      id: searchForm.id || undefined,
      guideId: searchForm.guideId || undefined,
      status: searchForm.status || undefined,
      startDate,
      endDate
    }
    
    const response = await getGuideAppointmentPage(currentPage.value, pageSize.value, params)
    
    // 处理列表数据，补充讲解员和时间段信息
    if (response.records && response.records.length > 0) {
      appointmentList.value = response.records.map(appointment => {
        return {
          ...appointment,
          guideName: appointment.guideName || getGuideName(appointment.guideId),
          timeSlotName: appointment.timeSlotName || getTimeSlotName(appointment.timeSlotId)
        }
      })
    } else {
      appointmentList.value = []
    }
    
    total.value = response.total
  } catch (error) {
    console.error('获取预约列表失败', error)
    ElMessage.error('获取预约列表失败')
  } finally {
    loading.value = false
  }
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'PENDING': '待审核',
    'APPROVED': '已通过',
    'REJECTED': '已拒绝',
    'CANCELED': '已取消'
  }
  return statusMap[status] || '未知状态'
}

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    'PENDING': 'warning',
    'APPROVED': 'success',
    'REJECTED': 'danger',
    'CANCELED': 'info'
  }
  return typeMap[status] || ''
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchAppointmentList()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = key === 'appointmentDate' ? [] : ''
  })
  currentPage.value = 1
  fetchAppointmentList()
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchAppointmentList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchAppointmentList()
}

// 查看详情 - 增强处理详情回显
const handleDetail = async (row) => {
  try {
    // 获取最新详情
    const response = await getGuideAppointmentById(row.id)
    if (response) {
      // 基础数据
      Object.keys(detailData).forEach(key => {
        detailData[key] = response[key] || ''
      })
      
      // 补充讲解员名称和时间段信息
      if (response.guideId && !response.guideName) {
        detailData.guideName = getGuideName(response.guideId)
      }
      
      if (response.timeSlotId && !response.timeSlotName) {
        detailData.timeSlotName = getTimeSlotName(response.timeSlotId)
      }
      
      detailDialogVisible.value = true
    }
  } catch (error) {
    console.error('获取预约详情失败', error)
    ElMessage.error('获取预约详情失败')
  }
}

// 获取所有可用的讲解员
const fetchAvailableGuides = async () => {
  try {
    const response = await getAllGuides()
    // 过滤出状态为启用的讲解员
    availableGuides.value = response.data.filter(guide => guide.status === 1) || []
  } catch (error) {
    console.error('获取讲解员列表失败', error)
    ElMessage.error('获取讲解员列表失败')
  }
}

// 打开分配讲解员弹窗 - 增强处理时间段显示
const handleAssignGuide = async (row) => {
  // 获取可用讲解员列表
  await fetchAvailableGuides()
  
  // 设置表单初始值
  assignForm.appointmentId = row.id
  assignForm.visitorName = row.visitorName
  assignForm.appointmentDate = row.appointmentDate + ' ' + (row.timeSlotName || getTimeSlotName(row.timeSlotId))
  assignForm.guideId = row.guideId || ''
  assignForm.remark = ''
  
  // 显示弹窗
  assignDialogVisible.value = true
}

// 提交分配
const submitAssignment = async () => {
  if (!assignForm.guideId) {
    ElMessage.warning('请选择讲解员')
    return
  }
  
  submitting.value = true
  try {
    // 获取当前预约详情
    const appointmentDetail = await getGuideAppointmentById(assignForm.appointmentId)
    
    // 准备更新数据
    const updateData = {
      id: assignForm.appointmentId,
      guideId: assignForm.guideId,
      status: 'APPROVED', // 设置状态为已通过
      remark: assignForm.remark
    }
    
    // 使用saveGuideAppointment方法更新预约信息
    const response = await saveGuideAppointment(updateData)
    
      ElMessage.success('讲解员分配成功')
      assignDialogVisible.value = false
      fetchAppointmentList() // 刷新列表
  } catch (error) {
    console.error('分配讲解员失败', error)
    ElMessage.error('分配讲解员失败')
  } finally {
    submitting.value = false
  }
}

// 拒绝预约
const handleCancel = (row) => {
  ElMessageBox.prompt('请输入拒绝原因', '拒绝预约', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPlaceholder: '请输入拒绝原因',
    type: 'warning'
  }).then(async ({ value }) => {
    try {
      const response = await approveGuideAppointment(row.id, 'REJECTED', value || '管理员拒绝')
      if (response.code === 200) {
        ElMessage.success('已拒绝该预约')
        fetchAppointmentList()
      } else {
        ElMessage.error(response.message || '操作失败')
      }
    } catch (error) {
      console.error('操作失败', error)
      ElMessage.error('操作失败')
    }
  }).catch(() => {})
}
</script>

<style scoped>
.guide-appointment-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  font-size: 22px;
  font-weight: 600;
  margin: 0;
  color: #2c3e50;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style> 